package com.ankiang.treeprint.fragment.components;

import android.os.Bundle;
import android.text.InputType;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.ankiang.treeprint.R;
import com.ankiang.treeprint.base.BaseFragment;
import com.ankiang.treeprint.lib.Group;
import com.ankiang.treeprint.lib.TRDataManager;
import com.ankiang.treeprint.lib.annotation.Widget;
import com.ankiang.treeprint.model.LOG;
import com.ankiang.treeprint.model.TRGroupItem;
import com.ankiang.treeprint.model.TRItemNode;
import com.ankiang.treeprint.view.TRConfig;
import com.ankiang.treeprint.view.TRListener;
import com.qmuiteam.qmui.alpha.QMUIAlphaImageButton;
import com.qmuiteam.qmui.util.QMUIDisplayHelper;
import com.qmuiteam.qmui.util.QMUIViewHelper;
import com.qmuiteam.qmui.widget.QMUITopBarLayout;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.qmuiteam.qmui.widget.grouplist.QMUICommonListItemView;
import com.qmuiteam.qmui.widget.grouplist.QMUIGroupListView;
import com.qmuiteam.qmui.widget.popup.QMUIListPopup;
import com.qmuiteam.qmui.widget.popup.QMUIPopup;

import org.devio.takephoto.app.TakePhotoFragment;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * {@link QMUIGroupListView} 的使用示例。
 * Created by Kayo on 2016/11/21.
 */


@Widget(group = Group.Seekpic, widgetClass = TRTimeFlyFragment.class, iconRes = R.drawable.group_image)
public class TRAddGroupFragment extends BaseFragment {

    // 操作状态
    public static final int EDIT = 1;
    public static final int ADD = 2;

    public static final String KEY_TAG = "KEY_TAG";
    public static final String KEY_DATA = "KEY_DATA";
//    public static final String KEY_OTHER_DATA = "KEY_OTHER_DATA";


    @BindView(R.id.topbar)
    QMUITopBarLayout mTopBar;

    @BindView(R.id.groupListView)
    QMUIGroupListView mGroupListView;


    // 分组名称
    @BindView(R.id.item_name)
    TextView itemNameTextView;

    @BindView(R.id.item_id)
    TextView itemIdTextView;


    @BindView(R.id.item_image)
    ImageButton itemImageButton;

    @BindView(R.id.item_remark)
    TextView itemRemarkTextView;

//    @BindView(R.id.done_button)
//    QMUIRoundButton doneButton;


    // 右上角列表
    private QMUIListPopup mListPopup;
    private QMUIAlphaImageButton mRightButton;


    // 保存数据
//    private int itemId;


    // 配置
    private TRConfig conf;
    private int mOp = ADD;
    private TRListener afterOperationListener;

    private TRGroupItem mData;

    TRDataManager dataManager;
    int tag;


    @Override
    protected View onCreateView() {
        View root = LayoutInflater.from(getActivity()).inflate(R.layout.tr_fragment_add_group, null);
        ButterKnife.bind(this, root);

        conf = TRConfig.getInstance();
        dataManager = TRDataManager.getInstance(getContext());

        Bundle bundle = getArguments();
        if (bundle != null) {
            tag = bundle.getInt(KEY_TAG);
            mData = (TRGroupItem) bundle.getSerializable(KEY_DATA);
        } else {
            tag = 0;
            mData = new TRGroupItem();
        }


        initTopBar();

        initGroupListView();

        initListener();
        if(mOp == ADD){
            showEditNameDialog();
        }
        return root;
    }

    public void setOp(int op) {
        this.mOp = op;
    }

    private void initListener() {


        if (itemNameTextView != null) {
            itemNameTextView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showEditNameDialog();
                }
            });
        }

        if (itemRemarkTextView != null) {
            itemRemarkTextView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showEditRemarkDialog();
                }
            });
        }

        if (itemImageButton != null) {
            itemImageButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showEditImageDialog();
                }
            });
        }
    }

    private void initTopBar() {


        mTopBar.setOnLongClickListener(v->{
            TRShowTextFragment fragment = new TRShowTextFragment();
            fragment.setOp(TRShowTextFragment.OP_SHOW_GROUP);
            fragment.setId(mData.getId());
            startFragment(fragment);
            return true;
        });

        mTopBar.addRightTextButton(R.string.done, QMUIViewHelper.generateViewId())
                .setOnClickListener(v -> {
                    done();
                });

        mTopBar.addLeftBackImageButton()
                .setOnClickListener(v -> {
                    cancel();
                });
        mTopBar.setTitle(R.string.tree_op_add_group);


        mTopBar.setTitle(R.string.details);
    }


    private void initGroupListView() {


        if (mOp == ADD) {
//            mData = new TRGroupItem();
//            mData.setId(dataManager.getNextGroupId());
            mTopBar.setTitle(V(R.string.tree_op_add_group));
        } else {
            LOG.jLogi("ItemId=%d", mData.getId());
//            mData = dataManager.getGroup(itemId);
            mTopBar.setTitle(V(R.string.details));
        }


        if (mData == null) {
            LOG.jLogi("itemTree[itemId]=null");
        }

        int id = mData.getId();

        String name = mData.getName();

        String remark = mData.getNote();
        if (remark == null || "".equals(remark)) {
            remark = TRItemNode.getNone();
        }
        String image = mData.getImage();

        itemNameTextView.setText(name);
        itemIdTextView.setText(String.format(V(R.string.details_id_format), id));

        itemRemarkTextView.setText(remark);

        itemNameTextView.setText(name);

        // todo itemImageButton not set yet

        int imgid = conf.getGroupItemId();
        itemImageButton.setImageResource(imgid);

        View.OnClickListener onClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (v instanceof QMUICommonListItemView) {
                    CharSequence text = ((QMUICommonListItemView) v).getText();
                    Toast.makeText(getActivity(), text + " is Clicked", Toast.LENGTH_SHORT).show();
                }
            }
        };

    }




    // 取消确认弹窗
    private void showMessageNegativeDialog() {
        new QMUIDialog.MessageDialogBuilder(getActivity())
                .setTitle(V(R.string.cancel))
                .setMessage(V(R.string.add_cancel_confirm_tips))
                .addAction(V(R.string.cancel), new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                    }
                })
                .addAction(0, V(R.string.ok), QMUIDialogAction.ACTION_PROP_NEGATIVE, new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {

                        dialog.dismiss();

                        popBackStack();
                    }
                })
                .create().show();
    }


    private void showEditNameDialog() {
        final QMUIDialog.EditTextDialogBuilder builder = new QMUIDialog.EditTextDialogBuilder(getActivity());
        String s = mData.getName();
        if (mData.isNameEmpty()) {
            s = "";
        }
        builder.setTitle(V(R.string.group_name))
                .setPlaceholder(V(R.string.additem_enter_content_tips))
                .setInputType(InputType.TYPE_CLASS_TEXT)
                .setDefaultText(s)
                .addAction(V(R.string.cancel), new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                    }
                })
                .addAction(V(R.string.ok), new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        CharSequence text = builder.getEditText().getText();
                        if (text != null && text.length() > 0) {
                            mData.setName(text.toString());
                            itemNameTextView.setText(text);

                            dialog.dismiss();
                        } else {
                            Toast.makeText(getActivity(), V(R.string.additem_enter_content_tips), Toast.LENGTH_SHORT).show();
                        }
                    }
                })
                .create().show();
    }


    private void showEditRemarkDialog() {
        final QMUIDialog.EditTextDialogBuilder builder = new QMUIDialog.EditTextDialogBuilder(getActivity());
        String s = mData.getNote();
        if (mData.isNoteEmpty()) {
            s = "";
        }
        builder.setTitle(V(R.string.additem_remark))
                .setPlaceholder(V(R.string.additem_enter_content_tips))
                .setInputType(InputType.TYPE_TEXT_VARIATION_LONG_MESSAGE)
                .setDefaultText(s)
                .addAction(V(R.string.cancel), new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                    }
                })
                .addAction(V(R.string.ok), new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        CharSequence text = builder.getEditText().getText();
                        if (text != null && text.length() > 0) {
                            mData.setNote(text.toString());
                            itemRemarkTextView.setText(text);

                            dialog.dismiss();
                        } else {
                            Toast.makeText(getActivity(), V(R.string.additem_enter_content_tips), Toast.LENGTH_SHORT).show();
                        }
                    }
                })
                .create().show();
    }



    // --------------------------------------------------
    // 操作
    private void showBottomSheet() {

        View v = mRightButton;
        initListPopupIfNeed();
        mListPopup.setAnimStyle(QMUIPopup.ANIM_GROW_FROM_CENTER);
        mListPopup.setPreferredDirection(QMUIPopup.DIRECTION_TOP);
        mListPopup.show(v);
    }


    private void initListPopupIfNeed() {
        if (mListPopup == null) {

            String[] listItems = new String[]{
                    V(R.string.details_op_delete)
            };
            List<String> data = new ArrayList<>();

            Collections.addAll(data, listItems);
            if (mOp == EDIT) {
                data.add(V(R.string.home_op_save));
            }

            ArrayAdapter adapter = new ArrayAdapter<>(getContext(), R.layout.simple_list_item, data);

            mListPopup = new QMUIListPopup(getContext(), QMUIPopup.DIRECTION_NONE, adapter);
            mListPopup.create(QMUIDisplayHelper.dp2px(getContext(), 120), QMUIDisplayHelper.dp2px(getContext(), 250), new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    //Toast.makeText(getContext(), "Item " + (i + 1), Toast.LENGTH_SHORT).show();

                    switch (i) {
                        case 0:
                            showMessageNegativeDeleteDialog(mData.getId());
                            // 删除
                            break;
                        case 1:
                            dataManager.save();
                            Toast.makeText(getContext(), V(R.string.save_success_tips), Toast.LENGTH_SHORT).show();
                            // 删除
                            break;
                    }
                    mListPopup.dismiss();
                }
            });
            mListPopup.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                }
            });
        }
    }


    private void showEditImageDialog() {

        TakePhotoFragment fragment = new TakePhotoFragment();
        fragment.setImageButton(itemImageButton);
        fragment.setOp(TakePhotoFragment.OP_CHOOSE_GROUP_IMAGE);

        Bundle bundle = new Bundle();
        bundle.putInt(TRAddItemFragment.KEY_TAG, tag);
        TRGroupItem data = this.mData;

        bundle.putSerializable(TRAddItemFragment.KEY_DATA, data);
        fragment.setArguments(bundle);

        this.startFragment(fragment);

    }


    public void setAfterOperation(TRListener listener) {
        this.afterOperationListener = listener;
    }


    // 删除分组确认弹窗
    private void showMessageNegativeDeleteDialog(final int itemId) {

        new QMUIDialog.MessageDialogBuilder(getActivity())
                .setTitle(V(R.string.details_op_delete))
                .setMessage(V(R.string.details_op_delete_confirm_tips))
                .addAction(V(R.string.details_op_cancel), new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                    }
                })
                .addAction(0, V(R.string.details_op_delete), QMUIDialogAction.ACTION_PROP_NEGATIVE, new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {

                        Toast.makeText(getActivity(), V(R.string.details_op_delete_success), Toast.LENGTH_SHORT).show();
                        dialog.dismiss();

                        // 保存数据
                        dataManager.deleteData(itemId);
                        popBackStack();
                        TRAddGroupFragment.this.runCallback(itemId);
                    }
                })
                .create().show();
    }


    /**
     * 保存数据并退出当前页面
     */
    private void done() {

        mData.refreshUpdatetime();
        dataManager.setGroup(mData.getId(), mData);

        if (afterOperationListener != null) {
            afterOperationListener.afterOperation(mData.getId());
        }
        popBackStack();

    }


    /**
     * 取消操作
     */
    private void cancel() {
        if (mOp == EDIT && dataManager.getGroup(mData.getId()).compareTo(mData) == 0) {
            popBackStack();
            return;
        } else {
            showMessageNegativeDialog();
        }
    }
}
